<template>
  <div class="banner-management tech-page">
    <!-- 页面头部 -->
    <div class="page-header tech-card">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title gradient-text">🎨 Banner管理</h1>
          <p class="page-subtitle">管理小程序首页Banner，支持图片上传、跳转链接设置、时间控制等功能</p>
        </div>
        <div class="stats-section">
          <div class="stat-item">
            <div class="stat-number">{{ bannerList.length }}</div>
            <div class="stat-label">总Banner数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ activeBannerCount }}</div>
            <div class="stat-label">启用中</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-section tech-card">
      <div class="search-header">
        <h3 class="search-title">🔍 筛选搜索</h3>
      </div>
      <div class="search-form">
        <div class="search-row">
          <div class="search-item">
            <label class="search-label">标题搜索</label>
            <el-input 
              v-model="searchForm.keyword" 
              placeholder="搜索Banner标题" 
              clearable
              class="tech-input"
              @change="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="search-item">
            <label class="search-label">状态筛选</label>
            <el-select 
              v-model="searchForm.status" 
              placeholder="选择状态" 
              clearable 
              class="tech-select"
              @change="handleSearch"
            >
              <el-option label="全部" value="" />
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </div>
          <div class="search-actions">
            <el-button class="tech-btn primary" @click="openDialog()">
              <el-icon><Plus /></el-icon>
              新增Banner
            </el-button>
            <el-button class="tech-btn outline" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- Banner列表 -->
    <el-card>
      <el-table :data="bannerList" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="图片" width="150">
          <template #default="scope">
            <el-image 
              :src="getFullImageUrl(scope.row.image_url)" 
              style="width: 120px; height: 60px;" 
              fit="cover" 
              :preview-src-list="[getFullImageUrl(scope.row.image_url)]"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><PictureIcon /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="基本信息" min-width="200">
          <template #default="scope">
            <div>
              <div class="banner-title">{{ scope.row.title }}</div>
              <div class="banner-desc">{{ scope.row.description }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="跳转设置" min-width="200">
          <template #default="scope">
            <el-tag :type="getLinkTypeColor(scope.row.link_type)">
              {{ getLinkTypeText(scope.row.link_type) }}
            </el-tag>
            <div v-if="scope.row.link_url" class="link-url">
              链接: {{ scope.row.link_url }}
            </div>
            <div v-if="scope.row.link_target" class="link-target">
              目标: {{ scope.row.link_target }}
            </div>
            <div v-if="scope.row.link_appid" class="link-appid">
              AppID: {{ scope.row.link_appid }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="点击数" width="80">
          <template #default="scope">
            <el-text type="primary">{{ scope.row.click_count || 0 }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="openDialog(scope.row)" icon="Edit">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)" icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑Banner弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑Banner' : '新增Banner'" 
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入Banner标题" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序序号" prop="sort_order">
              <el-input-number v-model="form.sort_order" :min="0" :max="999" placeholder="数字越小越靠前" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入Banner描述" 
            maxlength="200" 
            show-word-limit 
          />
        </el-form-item>

        <el-form-item label="Banner图片" prop="image_url">
          <el-upload
            class="banner-uploader"
            action="/api/v1/admin/banners/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :headers="uploadHeaders"
            accept="image/*"
          >
            <img v-if="form.image_url" :src="getFullImageUrl(form.image_url)" class="banner-image" />
            <div v-else class="upload-placeholder">
              <el-icon class="banner-upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击上传图片</div>
              <div class="upload-hint">支持 jpg、png、gif，大小不超过2MB</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="跳转类型" prop="link_type">
          <el-radio-group v-model="form.link_type" @change="handleLinkTypeChange">
            <el-radio value="external">外部链接</el-radio>
            <el-radio value="internal">内部页面</el-radio>
            <el-radio value="venue">场馆详情</el-radio>
            <el-radio value="miniprogram">小程序跳转</el-radio>
            <el-radio value="none">纯展示</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.link_type === 'external'" label="跳转链接" prop="link_url">
          <el-input v-model="form.link_url" placeholder="请输入完整的HTTP链接" />
        </el-form-item>

        <el-form-item v-if="form.link_type === 'internal'" label="页面路径" prop="link_target">
          <el-input v-model="form.link_target" placeholder="如：/venues、/activities" />
        </el-form-item>

        <el-form-item v-if="form.link_type === 'venue'" label="场馆ID" prop="link_target">
          <el-input v-model="form.link_target" placeholder="请输入场馆ID" />
        </el-form-item>

        <el-form-item v-if="form.link_type === 'miniprogram'" label="小程序AppID" prop="link_appid">
          <el-input v-model="form.link_appid" placeholder="请输入目标小程序的AppID" />
        </el-form-item>

        <el-form-item v-if="form.link_type === 'miniprogram'" label="小程序页面路径" prop="link_target">
          <el-input v-model="form.link_target" placeholder="如：pages/index/index" />
        </el-form-item>

        <el-form-item v-if="form.link_type === 'none'" class="none-type-tip">
          <el-alert
            title="纯展示模式"
            description="该Banner仅用于图片展示，点击时不会执行任何跳转操作"
            type="info"
            :closable="false"
            show-icon
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="form.start_time"
                type="datetime"
                placeholder="选择开始展示时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="form.end_time"
                type="datetime"
                placeholder="选择结束展示时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete, Picture, Refresh } from '@element-plus/icons-vue'
import request from '@/utils/request'

export default {
  name: 'BannerList',
  components: { 
    Plus, Search, Edit, Delete, PictureIcon: Picture, Refresh 
  },
  setup() {
    const apiBaseUrl = window.location.origin
    const bannerList = ref([])
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      status: ''
    })

    // 分页
    const pagination = reactive({
      page: 1,
      per_page: 10,
      total: 0
    })

    // 表单数据
    const form = reactive({
      id: null,
      title: '',
      description: '',
      image_url: '',
      link_url: '',
      link_type: 'external',
      link_target: '',
      link_appid: '',
      sort_order: 0,
      status: 1,
      start_time: '',
      end_time: ''
    })

    // 表单验证规则
    const rules = {
      title: [{ required: true, message: '请输入Banner标题', trigger: 'blur' }],
      image_url: [{ required: true, message: '请上传Banner图片', trigger: 'change' }],
      link_url: [
        {
          validator: (rule, value, callback) => {
            if (form.link_type === 'external') {
              if (!value) {
                callback(new Error('请输入跳转链接'))
              } else if (!/^https?:\/\//.test(value)) {
                callback(new Error('链接必须以http://或https://开头'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      link_target: [
        {
          validator: (rule, value, callback) => {
            if (form.link_type === 'internal') {
              if (!value) {
                callback(new Error('请输入页面路径'))
              } else if (!value.startsWith('/')) {
                callback(new Error('页面路径必须以"/"开头'))
              } else {
                callback()
              }
            } else if (form.link_type === 'venue') {
              if (!value) {
                callback(new Error('请输入场馆ID'))
              } else if (!/^\d+$/.test(value)) {
                callback(new Error('场馆ID必须为数字'))
              } else {
                callback()
              }
            } else if (form.link_type === 'miniprogram') {
              if (!value) {
                callback(new Error('请输入小程序页面路径'))
              } else if (!value.startsWith('pages/')) {
                callback(new Error('小程序页面路径应以"pages/"开头'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      link_appid: [
        {
          validator: (rule, value, callback) => {
            if (form.link_type === 'miniprogram') {
              if (!value) {
                callback(new Error('请输入小程序AppID'))
              } else if (!/^wx[a-zA-Z0-9]{16}$/.test(value)) {
                callback(new Error('小程序AppID格式不正确，应为wx开头的18位字符'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      sort_order: [
        {
          validator: (rule, value, callback) => {
            if (value !== null && value !== undefined && value !== '') {
              if (!/^\d+$/.test(value.toString()) || parseInt(value) < 0) {
                callback(new Error('排序序号必须为非负整数'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    const formRef = ref(null)
    
    // 上传头部信息
    const uploadHeaders = computed(() => ({
      Authorization: `Bearer ${localStorage.getItem('admin_token')}`
    }))

    // 获取Banner列表
    const fetchBannerList = async () => {
      loading.value = true
      try {
        const token = localStorage.getItem('admin_token')
        const params = {
          page: pagination.page,
          per_page: pagination.per_page,
          ...searchForm
        }
        
        const response = await request.get('/v1/admin/banners', { params })

        if (response.code === 200) {
          bannerList.value = response.data.banners || []
          pagination.total = response.data.total || 0
        }
      } catch (error) {
        console.error('获取Banner列表失败:', error)
        ElMessage.error('获取Banner列表失败')
      } finally {
        loading.value = false
      }
    }

    // 打开对话框
    const openDialog = (banner = null) => {
      isEdit.value = !!banner
      if (banner) {
        // 处理图片URL，确保显示完整的URL - 通过后端API域名访问
        const imageUrl = banner.image_url && banner.image_url.startsWith('http') 
          ? banner.image_url 
          : `https://hm.yunxitech.cn${banner.image_url}`
        
        Object.assign(form, {
          id: banner.id,
          title: banner.title,
          description: banner.description,
          image_url: imageUrl,
          link_url: banner.link_url,
          link_type: banner.link_type,
          link_target: banner.link_target,
          link_appid: banner.link_appid || '',
          sort_order: banner.sort_order,
          status: banner.status,
          start_time: banner.start_time ? banner.start_time.replace('Z', '') : '',
          end_time: banner.end_time ? banner.end_time.replace('Z', '') : ''
        })
      } else {
        Object.assign(form, {
          id: null,
          title: '',
          description: '',
          image_url: '',
          link_url: '',
          link_type: 'external',
          link_target: '',
          link_appid: '',
          sort_order: 0,
          status: 1,
          start_time: '',
          end_time: ''
        })
      }
      dialogVisible.value = true
    }

    // 提交表单
    const handleSubmit = () => {
      formRef.value?.validate(async (valid) => {
        if (!valid) return

        submitLoading.value = true
        try {
          const token = localStorage.getItem('admin_token')
          const data = { ...form }
          
          // 处理时间格式
          if (data.start_time) {
            data.start_time = data.start_time + ':00Z'
          }
          if (data.end_time) {
            data.end_time = data.end_time + ':00Z'
          }

          if (isEdit.value) {
            await request.put(`/v1/admin/banners/${form.id}`, data)
            ElMessage.success('更新成功')
          } else {
            await request.post('/v1/admin/banners', data)
            ElMessage.success('创建成功')
          }
          
          dialogVisible.value = false
          fetchBannerList()
        } catch (error) {
          console.error('操作失败:', error)
          ElMessage.error('操作失败')
        } finally {
          submitLoading.value = false
        }
      })
    }

    // 删除Banner
    const handleDelete = (banner) => {
      ElMessageBox.confirm(
        `确定要删除Banner "${banner.title}" 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const token = localStorage.getItem('admin_token')
          await request.delete(`/v1/admin/banners/${banner.id}`)
          ElMessage.success('删除成功')
          fetchBannerList()
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      })
    }

    // 状态切换
    const handleStatusChange = async (banner) => {
      try {
        const token = localStorage.getItem('admin_token')
        await request.put(`/v1/admin/banners/${banner.id}/status`, {
          status: banner.status
        })
        ElMessage.success(`已${banner.status ? '启用' : '禁用'}`)
      } catch (error) {
        console.error('状态切换失败:', error)
        ElMessage.error('操作失败')
        // 恢复原状态
        banner.status = banner.status === 1 ? 0 : 1
      }
    }

    // 上传成功回调
    const handleUploadSuccess = (response) => {
      if (response.code === 200) {
        // 构建完整的图片URL - 通过后端API域名访问
        form.image_url = `https://hh.yunxitech.cn${response.data.url}`
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.error('图片上传失败')
      }
    }

    // 上传前验证
    const beforeUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过2MB！')
        return false
      }
      return true
    }

    // 跳转类型改变
    const handleLinkTypeChange = () => {
      form.link_url = ''
      form.link_target = ''
      form.link_appid = ''
    }

    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      fetchBannerList()
    }

    // 刷新
    const handleRefresh = () => {
      searchForm.keyword = ''
      searchForm.status = ''
      pagination.page = 1
      fetchBannerList()
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.per_page = size
      pagination.page = 1
      fetchBannerList()
    }

    const handleCurrentChange = (page) => {
      pagination.page = page
      fetchBannerList()
    }

    // 工具函数
    const getLinkTypeColor = (type) => {
      const colors = {
        'external': 'primary',
        'internal': 'success',
        'venue': 'warning',
        'miniprogram': 'danger',
        'none': 'info'
      }
      return colors[type] || 'info'
    }

    const getLinkTypeText = (type) => {
      const texts = {
        'external': '外部链接',
        'internal': '内部页面',
        'venue': '场馆详情',
        'miniprogram': '小程序跳转',
        'none': '纯展示'
      }
      return texts[type] || '未知'
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    // 获取完整的图片URL
    const getFullImageUrl = (url) => {
      if (!url) return '';
      // 如果已经是完整的 http/https 链接，直接返回
      if (/^https?:\/\//.test(url)) {
        return url;
      }
      // 否则，都拼接正确的后端地址
      const backendUrl = 'https://dpcurdgwzmkg.sealosbja.site';
      // 确保 url 是以 / 开头的相对路径
      const relativeUrl = url.startsWith('/') ? url : `/${url}`;
      return `${backendUrl}${relativeUrl}`;
    }

    onMounted(() => {
      fetchBannerList()
    })

    return {
      apiBaseUrl,
      bannerList,
      loading,
      submitLoading,
      dialogVisible,
      isEdit,
      searchForm,
      pagination,
      form,
      rules,
      formRef,
      uploadHeaders,
      openDialog,
      handleSubmit,
      handleDelete,
      handleStatusChange,
      handleUploadSuccess,
      beforeUpload,
      handleLinkTypeChange,
      handleSearch,
      handleRefresh,
      handleSizeChange,
      handleCurrentChange,
      getLinkTypeColor,
      getLinkTypeText,
      formatDateTime,
      getFullImageUrl
    }
  }
}
</script>

<style scoped>
.banner-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.banner-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.banner-desc {
  font-size: 12px;
  color: #909399;
}

.link-url, .link-target {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}

.link-appid {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}

.none-type-tip {
  margin-bottom: 0;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.banner-uploader {
  display: inline-block;
}

.banner-image {
  width: 300px;
  height: 150px;
  object-fit: cover;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
}

.upload-placeholder {
  width: 300px;
  height: 150px;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-placeholder:hover {
  border-color: #409eff;
}

.banner-upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.upload-hint {
  color: #c0c4cc;
  font-size: 12px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 14px;
}
</style> 